package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shenb
 * @date 2022-08-19 11:08
 */
@Component
@WebFilter(filterName = "jwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(JwtFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("JwtFilter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        if (requestURI.startsWith("/authenticate")) {
            chain.doFilter(request, response);
            return;
        }

        try {
            String authentication = req.getHeader("Authorization");
            if (authentication == null || authentication.isEmpty()) {
                throw new RuntimeException("Authorization header not exists");
            }
            String token = authentication.replace("Bearer ", "");
            String username = JwtTokenUtil.verity(token);
            request.setAttribute("Login-User", username);
            log.info("login user: {}", username);
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("Unauthorized", e);
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
        }
    }

    @Override
    public void destroy() {
        log.info("JwtFilter destroy");
    }
}
